package com.jade.framework.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.sql.DataSource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: jade
 * @description:
 * @author: wupujian
 * @create: 2020-04-29 15:10
 **/

//@Configuration
public class CustomizeDataSourceInitializer {

//    @Value("classpath:sql/jadeproject.sql")
    private Resource functionScriptFarms;

//    @Value("${autu.testSql}")
    private String testSql;

//    @Value("${autu.sql}")
    private String sql;

//    @Value("${autu.switch}")
    private String autuSwitch;

//    @Bean
    public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {
        final DataSourceInitializer initializer = new DataSourceInitializer();
        // 设置数据源
        initializer.setDataSource(dataSource);
        try {
        	if(StringUtils.equals("true", autuSwitch)){
        		System.out.println("开始尝试初始化数据库");
        		Connection connection = dataSource.getConnection();
    			Statement createStatement = connection.createStatement();
    			
    			
    			try {
    				System.out.println("开始执行测试数据库脚本");
    				createStatement.execute(testSql);
    				System.out.println("无需执行初始化数据库脚本");
    			} catch (SQLException e) {
    				//表不存在
    				System.out.println("开始执行初始化数据库脚本");
    				List<Resource>   re=getrslist(sql);
    				for (Resource resource : re) {
    					 try {
							initializer.setDatabasePopulator(databasePopulator(resource));
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
    			}
        	}else{
        		System.out.println("开关关闭，不执行初始化数据库脚本");
        	}
		} catch (SQLException e) {
			e.printStackTrace();
		}

        return initializer;
    }
    
    private List<Resource> getrslist(String sql2) {
    	List<Resource> stringList=new ArrayList<Resource>();
		if(StringUtils.isNotBlank(sql2)){
			String[] split = sql2.split(";");
			for (String string : split) {
			
			Resource ClassPathResource=new  ClassPathResource(string);
			stringList.add(ClassPathResource);
			}
		}
    	return stringList;
	}

	/**
	 * 根据配置文件，取得所有sql文件的sql
	 * @return
	 */
	private List<String> getSqlList(String initSql) {
		List<String> stringList=new ArrayList<String>();
		if(StringUtils.isNotBlank(initSql)){
			String[] split = initSql.split(";");
			for (String string : split) {
				ClassPathResource classPathResource = new ClassPathResource(string);
				String sqlFile="";
				try {
					sqlFile = Resource2String(classPathResource);
				} catch (IOException e) {
					e.printStackTrace();
				}
				if(StringUtils.isNotBlank(sqlFile)){
					stringList.add(sqlFile);
				}
			}
		}
		return stringList;
	}
	

	/**
	 * ClassPathResource转换成String
	 * @param classPathResource
	 * @return
	 * @throws IOException
	 */
	private String Resource2String(ClassPathResource classPathResource) throws IOException {
		InputStream inputStream = classPathResource.getInputStream();
		  
		ByteArrayOutputStream bos = new ByteArrayOutputStream();  
		  
		//读取缓存  
		byte[] buffer = new byte[2048];  
		int length = 0;  
		while((length = inputStream.read(buffer)) != -1) {  
		    bos.write(buffer, 0, length);//写入输出流  
		}  
		inputStream.close();//读取完毕，关闭输入流  
		String string = bos.toString("UTF-8");
		return string;
	}
	
	/**
	 * ClassPathResource转换成String
	 * @param classPathResource
	 * @return
	 * @throws IOException
	 */
	private String Resource2String2(Resource classPathResource) throws IOException {
		InputStream inputStream =classPathResource.getInputStream();
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();  
		
		//读取缓存  
		byte[] buffer = new byte[2048];  
		int length = 0;  
		while((length = inputStream.read(buffer)) != -1) {  
			bos.write(buffer, 0, length);//写入输出流  
		}  
		inputStream.close();//读取完毕，关闭输入流  
		String string = bos.toString("UTF-8");
		return string;
	}
	
	
	 private DatabasePopulator databasePopulator(Resource rs) {
	        final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
	            populator.addScripts(rs);
	        return populator;
	    }

}
